import re

def preprocess(contents):
    return contents.replace('\\\n','').replace('    ','\t')
    
def level(content):
    i=0
    while i <len(content) and content[i]=='\t':
        i+=1
    return i

class Node:
    def __init__(self,level,content,typ):
        self.level=level
        self.content=content
        self.typ=typ
        self.parent=None
        self.sons=[]
    
    def setParent(self,parent):
        self.parent=parent

    def setSon(self,son):
        self.sons.append(son)

    def show(self):
        print(self.level,self.content)
        print('=====')
        for son in self.sons:
            son.show()

    def gend(self):
        d={'level':self.level,'content':self.content,'sons':[],'typ':self.typ}
        if self.typ=='class':
            searchResult=re.search(r'class\s+(\w+)\s*(\(?.+\)?)\s*:',self.content)
            if searchResult is not None:
                d['name']=searchResult.group(1)
                d['parent']=searchResult.group(2)[1:-1] if searchResult.group(2)[0]=='(' else 'object'
        elif self.typ=='func':
            searchResult=re.search(r'def\s+(\w+)\s*\((.*)\)\s*:',self.content)
            if searchResult is not None:
                d['name']=searchResult.group(1)
                d['params']=searchResult.group(2)
        for son in self.sons:
            if son.typ!='return':
                d['sons'].append(son.gend())
            else:
                searchResult=re.search(r'return\s+(.+)\s*',son.content)
                if searchResult is not None:
                    d['return']=searchResult.group(1)
        return d

def postprocess(ls):
    root=oldNode=Node(-1,'','file')
    for l in ls:
        node=Node(l[0],l[1],l[2])
        if node.level==oldNode.level:
            node.setParent(oldNode.parent)
            oldNode.parent.setSon(node)
        elif node.level>oldNode.level:
            node.setParent(oldNode)
            oldNode.setSon(node)
        else:
            for i in range(oldNode.level-node.level+1):
                oldNode=oldNode.parent
            node.setParent(oldNode)
            oldNode.setSon(node)
        oldNode=node
    fileDict=root.gend()
    print(fileDict)

def parse(file):
    with open(file,encoding='utf8') as f:
        contents=f.read()
    contents=preprocess(contents)
    ls=[]
    for content in contents.split('\n'):
        meaningfuls=content.split()
        if len(meaningfuls):
            if meaningfuls[0]=='class':
                ls.append((level(content),content,'class'))
            elif meaningfuls[0]=='def':
                ls.append((level(content),content,'func'))
            elif meaningfuls[0]=='return':
                ls.append((level(content),content,'return'))
    postprocess(ls)